import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, Upload, Popover, Popconfirm } from 'antd';
import MyIcon from '@/components/MyIcon';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import StandardTableForm from '@/components/StandardTable/StandardTableForm';
import StandardTableHandle from '@/components/StandardTable/StandardTableHandle';
import ImageCrop from '@/components/ImageCrop';
import { bannersCenter as columns } from '@/commons/columns';
import { bannersCenter as map } from '@/commons/map';
import { banners as tabList } from '@/commons/tabList';

const bannerUploadStyles = {
  width: 130,
  height: 130,
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'center',
}

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const disabledDate = current => current && current < moment().endOf('day');

const CreateForm = Form.create()(props => {
  const { modalVisible, queryRow = {}, form, handleAddOrUpdate, linkTo, handleLinkTo, handleModalVisible, handleUpload } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();

      handleAddOrUpdate({ ...fieldsValue, id: queryRow.id });
    });
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 19 },
    },
  };

  return (
    <Modal
      destroyOnClose
      width={500}
      title="新增广告"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={handleModalVisible.bind(null)}
    >
      <FormItem {...formItemLayout} label="广告图片">
        {form.getFieldDecorator('cover', {
          initialValue: queryRow.cover,
          rules: [{ required: true, message: '请输入选择广告图片！' }],
        })(
          <Fragment>
            <Input type="hidden" value={queryRow.cover} />
            <ImageCrop
              listType="picture-card"
              onUpload={handleUpload}
            >
              {
                queryRow.cover 
                ? 
                <img src={queryRow.cover + IMAGE_STYLE} width="200" />
                // <section style={bannerUploadStyles} style={{backgroundImage: 'url('+ queryRow.cover +')'}} /> 
                : 
                <Icon type="plus" />
              }
            </ImageCrop>
          </Fragment>
        )}
        <span>建议上传350x150尺寸的jpg/png图片</span>
      </FormItem>
      <FormItem {...formItemLayout} label="上架时间">
        {form.getFieldDecorator('startedAt', {
          initialValue: queryRow.startedAt ? moment(queryRow.startedAt) : null,
          rules: [{ required: true, message: '请输入上架时间！' }],
        })(<DatePicker placeholder="请输入上架时间" disabledDate={disabledDate} format="YYYY-MM-DD HH:mm:ss" showTime style={{width: '100%'}} />)}
      </FormItem>
      <FormItem {...formItemLayout} label="下架时间">
        {form.getFieldDecorator('endAt', {
          initialValue: queryRow.endAt ? moment(queryRow.endAt) : null,
          rules: [{ required: true, message: '请输入下架时间！' }],
        })(<DatePicker placeholder="请输入下架时间" disabledDate={disabledDate} format="YYYY-MM-DD HH:mm:ss" showTime style={{width: '100%'}} />)}
      </FormItem>
      <FormItem {...formItemLayout} label="跳转位置">
        <RadioGroup onChange={handleLinkTo} value={linkTo}>
          <Radio value='pathname'>链接地址</Radio>
          <Radio value='appId'>小程序 APPID</Radio>
        </RadioGroup>
        {
          linkTo === 'pathname'
          ?
          form.getFieldDecorator('pathname', {
            initialValue: queryRow.pathname,
            rules: [{ required: true, message: '请输入跳转链接！' }],
          })(<Input placeholder="请输入跳转链接" />)
          :
          linkTo === 'appId'
          ?
          form.getFieldDecorator('appId', {
            initialValue: queryRow.appId,
            rules: [{ required: true, message: '请输入小程序 APPID！' }],
          })(<Input placeholder="请输入小程序 APPID" />)
          :
          null
        }
      </FormItem>
      <FormItem {...formItemLayout} label="备注" style={{marginBottom: 0}}>
        {form.getFieldDecorator('remark', {
          initialValue: queryRow.remark,
          rules: [{ required: true, message: '请输入至少五个字符的备注内容！', min: 5 }],
        })(<TextArea placeholder="请输入备注内容" autosize={{ minRows: 5, maxRows: 6 }} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ bannerCenter, loading }) => ({
  bannerCenter,
  loading: loading.models.bannerCenter,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    queryRow: {},
    linkTo: 'pathname',
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: payload => (
      <Fragment>
        <Button 
          type="primary" 
          ghost 
          icon="edit" 
          size="small" 
          onClick={this.handleModalVisible.bind(null, payload)}
        >
        重新编辑
        </Button>
        {
          payload.status === 0 
          && 
          <Popconfirm 
            title="确认下架广告?" 
            okText="确认" 
            cancelText="取消"
            onConfirm={this.handleUpdate.bind(null, payload)} 
          >
            <Button
              type="primary"
              icon="arrow-down" 
              size="small"
              ghost
              style={{marginTop: 8}}
            >
              下架广告
            </Button>
          </Popconfirm>
        }
      </Fragment>
    )
  }];

  tabList = [...tabList];

  componentWillMount() {
    this.columns.splice(columns.length - 3, 0, {
      title: '点击量',
      dataIndex: 'click',
      align: 'center',
    });
  }

  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'bannerCenter/fetch',
    });
  }

  handleTabChange = type => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'bannerCenter/fetch',
      payload: { type },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'bannerCenter/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;

    form.resetFields();
    this.setState({
      formValues: {},
    });

    dispatch({
      type: 'bannerCenter/fetch'
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  // 删除广告 
  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'bannerCenter/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'bannerCenter/fetch',
              });
              this.setState({
                selectedRows: []
              });
              message.success(`共有${data}条广告删除成功~`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      case 'update':
        dispatch({
          type: 'bannerCenter/update',
          payload: { id: selectedRows.map(row => row.id), status: 1 },
          callback: ({ errno, data }) => {
            console.log(data)
            if (errno) {
              message.error('下架广告失败！');
            } else {
              dispatch({
                type: 'bannerCenter/fetch'
              });

              message.success(`共有${data}条广告下架成功~`);
            }
          }
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        endAt: fieldsValue.endAt && fieldsValue.endAt.format('YYYY-MM-DD hh:mm'),
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.format('YYYY-MM-DD hh:mm'),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.format('YYYY-MM-DD hh:mm'),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'bannerCenter/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (queryRow = {}) => {
    const payload = {};

    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalVisible: false,
        queryRow: {},
      });
    } else {
      Object.assign(payload, {
        modalVisible: true,
        queryRow,
      });
    }
    this.setState(state => ({
      ...state,
      ...payload,
    }));
  };

  handleLinkTo = e => {
    e.preventDefault();

    this.setState(state => ({
      ...state,
      linkTo: e.target.value
    }));
  };

  handleAddOrUpdate = fieldsValue => {
    const { dispatch } = this.props;

    const { file = {} } = fieldsValue.cover || {};
    const { data = {} } = file.response || {};

    const values = {
      ...fieldsValue,
      cover: typeof fieldsValue.cover === 'string' ? fieldsValue.cover : data.name,
      endAt: fieldsValue.endAt && fieldsValue.endAt.format('YYYY-MM-DD HH:mm:ss'),
      startedAt: fieldsValue.startedAt && fieldsValue.startedAt.format('YYYY-MM-DD HH:mm:ss'),
    }

    if (fieldsValue.id) {
      dispatch({
        type: 'bannerCenter/update',
        payload: { ...values, isEdit: true },
        callback: ({ errno, data }) => {
          if (errno) {
            message.error('更新失败！');
          } else {
            dispatch({
              type: 'bannerCenter/fetch',
            });

            message.success(`序号${fieldsValue.id}的广告更新成功~`);
          }
        }
      });
    } else {
      dispatch({
        type: 'bannerCenter/add',
        payload: values,
        callback: ({ errno, data }) => {
          if (errno) {
            message.error('新增失败！');
          } else {
            dispatch({
              type: 'bannerCenter/fetch',
            });

            message.success(`序号${data.id}的广告新增成功~`);
          }
        }
      });
    }

    this.handleModalVisible();
  }

  // 下架广告
  handleUpdate = payload => {
    const { dispatch } = this.props;

    dispatch({
      type: 'bannerCenter/update',
      payload: { id: payload.id, status: 1 },
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('下架广告失败！');
        } else {
          dispatch({ type: 'bannerCenter/fetch' });

          message.success(`序号${payload.id}的广告下架成功~`);
        }
      }
    });
  };

  handleToggleTable = e => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'bannerCenter/fetch',
      payload: { status: e.target.value }
    });
  }

  handleUpload = (info, callback) => {
    const { form, dispatch } = this.props;

    if (!info.errno) {
      this.setState(state => ({
        ...state,
        queryRow: { ...state.queryRow, cover: info.data.name },
      }), () => {
        console.log(this.state, 123)
        message.success(`路径${info.data.name}的banner图片上传成功！`);
      });
    }
  }

  render() {
    const {
      bannerCenter: { data, type, status },
      loading,
      form,
    } = this.props;
    const { expandForm, linkTo, queryRow, selectedRows, modalVisible, updateModalVisible, stepFormValues } = this.state;

    const parentMethods = {
      queryRow,
      modalVisible,
      handleAddOrUpdate: this.handleAddOrUpdate,
      linkTo,
      handleLinkTo: this.handleLinkTo,
      handleModalVisible: this.handleModalVisible,
      handleUpload: this.handleUpload,
    };
    return (
      <PageHeaderWrapper 
        title="广告中心" 
        action={moment().format('LLLL')}
      >
        <Card bordered={false}>
          <StandardTableForm
            expandForm={expandForm}
            data={map}
            form={form}
            onSubmit={this.handleSearch}
            onReset={this.handleFormReset}
            onToggle={this.toggleForm}
          />
          <StandardTableHandle
            status={status}
            selectedRows={selectedRows}
            radioGroups={{
              'all': <Fragment><MyIcon type="icon-all" />&nbsp;全部</Fragment>, 
              '0': <Fragment><MyIcon type="icon-expired" />&nbsp;未下架</Fragment>,
              '1': <Fragment><MyIcon type="icon-ongoing" />&nbsp;已下架</Fragment>,
            }}
            menuItems={{
              'remove': <Button type="danger" icon="delete" size="small" style={{width: '100%'}}>删除</Button>, 
              'update': <Button icon="arrow-down" size="small" style={{width: '100%'}}>下架</Button>
            }}
            action={
              <Fragment>
                {
                  status === '0'
                  ? 
                  <Button 
                    type="primary" 
                    icon="plus" 
                    key="2" 
                    style={{marginRight: 16, marginLeft: 8}} 
                    onClick={this.handleModalVisible.bind(null, {id:0})}
                  >新增</Button>
                  :
                  null
                }                
                <a href="/favicon.png" target="_blank">
                  <Button type="primary" icon="download">EXCEL</Button>
                </a>
              </Fragment>
            }
            onToggleTable={this.handleToggleTable}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            scroll={{ x: 1300 }}
            columns={this.columns}
            expandedRowRender={record => <p style={{ marginBottom: 0 }}>备注：{record.remark}</p>}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <CreateForm {...parentMethods} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;